package arithmetic.LeetCode;

import java.util.Arrays;

/**
 * 48. 旋转图像
 * 给定一个 n × n 的二维矩阵 matrix 表示一个图像。请你将图像顺时针旋转 90 度。
 *
 * 你必须在 原地 旋转图像，这意味着你需要直接修改输入的二维矩阵。请不要 使用另一个矩阵来旋转图像。
 *
 *
 * 示例 1：
 * 输入：matrix = [[1,2,3],[4,5,6],[7,8,9]]
 * 输出：[[7,4,1],[8,5,2],[9,6,3]]
 *
 * 示例 2：
 * 输入：matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]
 * 输出：[[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]
 * https://leetcode.cn/problems/rotate-image/?envType=study-plan-v2&id=top-100-liked
 * @author jiangfeng on 2023/5/13
 */
public class Rotate {
    public static void main(String[] args) {
        //int[][] a =new int[][]{{5,1,9,11},{2,4,8,10},{13,3,6,7},{15,14,12,16}};
        //int[][] a =new int[][]{{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
        int[][] a =new int[][]{{1,2,3},{4,5,6},{7,8,9}};
        print(a);
        new Solution().rotate(a);
        print(a);
        //System.out.println(Arrays.deepToString(a));
    }
    static class Solution {
        public void rotate(int[][] matrix) {
            int length  = matrix.length;
            if(length==1){
                return;
            }
            int circle = length/2;
            int j=0;
            int[] pos = new int[2];
            int pre=0,cur=0;

            int direction=0;
            while(j<circle){
                for(int i=j;i<length-1-j;i++){
                    getCurrent(matrix,j,i,length-1,3,pos);
                    pre = matrix[pos[0]][pos[1]];
                    direction = 0;
                    while(direction<4){
                        getCurrent(matrix,j,i,length-1,direction,pos);
                        cur = matrix[pos[0]][pos[1]];
                        matrix[pos[0]][pos[1]]=pre;
                        pre = cur;
                        direction++;
                    }
                }
                j++;
            }
        }
        // 状态机: 0,1,2,3, 取哪个方位的值.
        public void getCurrent(int[][] matrix,int i,int j,int length,int direction,int[] pos){
            switch(direction){
                case 0:
                    pos[0]=i;
                    pos[1]=j;
                    return;
                case 1:
                    pos[0]=j;
                    pos[1]=length-i;
                    return;
                case 2:
                    pos[0]=length-i;
                    pos[1]=length-j;
                    return;
                case 3:
                    pos[0]=length-j;
                    pos[1]=i;
                    return;
                default:
                    return;

            }
        }
    }

    static void print(int[][] matrix){
        System.out.println();
        for (int [] a:matrix){
            System.out.println(Arrays.toString(a));
        }
    }
}
